package com.cicoding.controller;


import javax.servlet.http.HttpServletRequest;

import com.cicoding.bean.User;
import com.cicoding.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cicoding.bean.ShiroUser;
import com.cicoding.constant.Constant;
import com.cicoding.log.LogManager;
import com.cicoding.log.LogTaskFactory;
import com.cicoding.utils.LinTools;
import com.cicoding.utils.MD5Util;
import com.cicoding.utils.Userinfo;

import java.util.Map;

@Controller
public class LoginController {
	
	private Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private LinTools linTools;
	@Autowired
	private UserService userService;
	@RequestMapping(value = "/login", method = { RequestMethod.POST })
	public String login(HttpServletRequest request, ShiroUser user) {
		Subject subject = SecurityUtils.getSubject();
		System.out.println(user.getUsername());
		System.out.println(user.getPassword());
		System.out.println(MD5Util.encrypt(user.getPassword()));
		user.setPassword(MD5Util.encrypt(user.getPassword()));
		ShiroUser user1 = userService.findUser(user.getUsername(),user.getPassword());
		if (user1 == null){
			request.setAttribute("status", Constant.ERROR_CODE_USERNAME_PASSWORD_MISMATCH);
			request.setAttribute("msg", "账号或密码错误");
			return "error";
		}
		request.getSession().setAttribute("id",user1.getId());
		request.getSession().setAttribute("grade",user1.getGrade());
		request.getSession().setAttribute("counts",user1.getCounts());
		request.getSession().setAttribute("password",user1.getPassword());
		request.getSession().setAttribute("salt",user1.getSalt());
		request.getSession().setAttribute("avator",user1.getAvator());
		request.getSession().setAttribute("username",user1.getUsername());
		request.getSession().setAttribute("deptid",user1.getDeptid());
		request.getSession().setAttribute("roleid",user1.getRoleid());
		if (linTools.getKaptchaSwich()) {
			String kaptchaRecevied = request.getParameter("kaptcha");
			// 用户输入的验证码的值
			String kaptchaExpected = (String) request.getSession()
					.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			// 校验验证码是否正确
			if (kaptchaRecevied == null || !kaptchaRecevied.equals(kaptchaExpected)) {
				request.setAttribute("msg", "验证码错误");
				request.setAttribute("status", Constant.ERROR_CODE_VERICATION_CODE_ERROR);
				return "error";// 返回验证码错误
			}

		}

		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
		try {
			subject.login(token);
		} catch (AuthenticationException e) {
			log.warn("登陆失败");
			System.out.println("进入到了异常处理");
			request.setAttribute("status", Constant.ERROR_CODE_USERNAME_PASSWORD_MISMATCH);
			request.setAttribute("msg", "账号或密码错误");
			LogManager.getInstance().saveLog(
					LogTaskFactory.getLoginFailTimerTask(user.getUsername(), "账号与密码不匹配", request.getRemoteHost()));
			return "error";
		}


		LogManager.getInstance().saveLog(LogTaskFactory.getLoginSuccessTimerTask(Userinfo.getUser().getId(),
				user.getUsername(), request.getRemoteHost()));


		return "redirect:/";
	}
	@RequestMapping(value = "/register", method = { RequestMethod.POST })
	public String register(HttpServletRequest request, String username,String password,String password2,String grade) {
//			String name = map.get("username");
//			String password = map.get("password");
//			String password2 = map.get("password2");
		int grade1 = Integer.parseInt(grade);
		System.out.println(username);
		System.out.println(password);
		System.out.println(password2);
		System.out.println(grade);
		if (linTools.getKaptchaSwich()) {
			String kaptchaRecevied = request.getParameter("kaptcha");
			// 用户输入的验证码的值
			String kaptchaExpected = (String) request.getSession()
					.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
			// 校验验证码是否正确
			if (kaptchaRecevied == null || !kaptchaRecevied.equals(kaptchaExpected)) {
				request.setAttribute("msg", "验证码错误");
				request.setAttribute("status", Constant.ERROR_CODE_VERICATION_CODE_ERROR);
				return "error";// 返回验证码错误
			}

		}

		if (!userService.userExistByName(username)){
			request.setAttribute("msg", "用户已存在");
			request.setAttribute("status", Constant.UNKNOWN_ERROR_CODE);
			return "error";
		}
		ShiroUser user = new ShiroUser();
		user.setUsername(username);
		user.setGrade(grade1);
		user.setPassword(MD5Util.encrypt(password));
		user.setAvator("1");
		user.setSalt("2");
		user.setDeptid(2);
		user.setRoleid(18);
		user.setCounts(1);
		userService.addUser(user);
		return "redirect:/";
	}
}
